<template>
	<view class="container">
        <u--form :labelStyle="{fontSize: '28rpx', color: '#312C2A', height: '80rpx'}"
                 labelWidth="100"
                 labelPosition="left"
                 :model="model"
                 :rules="rules"
                 ref="uForm"
                 errorType="message"
        >
			<view class="form">

				<u-form-item borderBottom prop="name">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a30.png')" ></u-image>
							<view class="">姓名</view>
						</view>
						<view class="right">
							<u--input inputAlign="right" placeholder="请输入您的姓名" v-model="model.name"
								border="none"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item borderBottom @click="showSex = true;" prop="sexName">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a44.png')" ></u-image>
							<view class="">性别</view>
						</view>
						<view class="right">
							<u--input v-model="model.sexName" disabled placeholder="请选择性别" inputAlign="right"
								disabledColor="transparent" border="none"></u--input>
							<template #right>
								<u-icon name="arrow-right"></u-icon>
							</template>
						</view>
					</view>
				</u-form-item>
				<u-form-item borderBottom prop="mobile">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a31.png')" ></u-image>
							<view class="">手机号</view>
						</view>
						<view class="right">
							<u--input inputAlign="right" placeholder="请输入您的手机号" v-model="model.mobile"
								border="none"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item borderBottom prop="address">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a45.png')" ></u-image>
							<view class="">住址</view>
						</view>
						<view class="right">
							<u--input inputAlign="right" placeholder="请输入您的住址" v-model="model.address"
								border="none"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item borderBottom prop="id_card">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a46.png')" ></u-image>
							<view class="">身份证号</view>
						</view>
						<view class="right">
							<u--input inputAlign="right" placeholder="请输入您的身份证号" v-model="model.id_card"
								border="none"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item borderBottom prop="medical_history">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a47.png')" ></u-image>
							<view class="">既往病史</view>
						</view>
						<view class="right">
							<u--input inputAlign="right" placeholder="请输入您的既往病史" v-model="model.medical_history"
								border="none"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item borderBottom prop="genetic_history">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a48.png')"></u-image>
							<view class="">遗传史</view>
						</view>
						<view class="right">
							<u--input inputAlign="right" placeholder="请输入您的遗传史" v-model="model.genetic_history"
								border="none"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item :borderBottom="false" @click="showRelationship = true;" prop="relationship">
					<view class="form-item">
						<view class="left">
							<u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a49.png')"></u-image>
							<view class="">就诊人关系</view>
						</view>
						<view class="right">
							<u--input v-model="model.relationship" disabled placeholder="选择就诊人关系" inputAlign="right"
								disabledColor="transparent" border="none"></u--input>
							<template #right>
								<u-icon name="arrow-right"></u-icon>
							</template>
						</view>
					</view>
				</u-form-item>
			</view>
		</u--form>
	</view>

	<view class="btn">
		<u-button :disabled="!disabled" throttleTime="1000"
			:customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}" :hairline="false"
			type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
			@click="confirm">
            <text v-if="patientId > 0">确认保存</text>
            <text v-else>确认添加</text>
        </u-button>
	</view>
	<!-- 性别选择框 -->
	<u-picker closeOnClickOverlay :show="showSex" :columns="actions" @cancel="showSex = false" @close="showSex = false" @confirm="sexSelect" keyName="name"></u-picker>

	<!-- 就诊人关系选择框 -->
	<u-picker closeOnClickOverlay :show="showRelationship" :columns="relationshipActions" @close="showRelationship = false" @cancel="showRelationship = false" @confirm="relationshipSelect" keyName="name"></u-picker>

</template>

<script setup>
    import {ref, reactive, readonly} from 'vue'
    import {onLoad, onShow, onReady} from '@dcloudio/uni-app'
    import {getPatient, savePatient} from "@/api/user";
    import useUniAPi from "@/hooks/useUniAPi";
    import {getToken} from "@/utils/cache";
    import {getAge, getServerStatic, validateIDNumber} from "@/utils/tool";
    const { navigateTo, redirectTo, goBack } = useUniAPi()
    const uForm = ref(null)

	const model = ref({
        name: '',
        sex: '',
        sexName: '',
        id_card: '',
        age: '',
        mobile: '',
        address: '',
        medical_history: '',
        genetic_history: '',
        relationship: '',
        is_myself: 0
	})

    const rules = ref({
        name: [
            {
                type: 'string',
                required: true,
                message: '请输入姓名',
                trigger: ['blur','change'],
            }
        ],
        sexName: [
            {
                type: 'string',
                required: true,
                message: '请选择性别',
                trigger: ['change'],
            }
        ],
        relationship: [
            {
                type: 'string',
                required: true,
                message: '请选择关系',
                trigger: ['change'],
            }
        ],
        id_card: [
            {
                type: 'string',
                required: true,
                message: '请输入证件号码',
                trigger: ['blur','change']
            },
            {
                validator: (rule, value, callback) => {
                    // 上面有说，返回true表示校验通过，返回false表示不通过
                    return uni.$u.test.idCard(value);
                },
                message: '证件号码不正确',
                // 触发器可以同时用blur和change
                trigger: ['change','blur'],
            }
        ],
        mobile: [
            {
                type: 'number',
                required: true,
                message: '请输入手机号',
                trigger: ['blur','change'],
            },
            {
                // 自定义验证函数，见上说明
                validator: (rule, value, callback) => {
                    // 上面有说，返回true表示校验通过，返回false表示不通过
                    // uni.$u.test.mobile()就是返回true或者false的
                    return uni.$u.test.mobile(value);
                },
                message: '手机号码不正确',
                // 触发器可以同时用blur和change
                trigger: ['change','blur'],
            }
        ]
    })


	const disabled = computed(() => {
		return model.value.name
	})
	const showSex = ref(false)
	const showRelationship = ref(false)
	const actions = ref([
		[
            {
				name: '男',
                value: 1,
			},
			{
				name: '女',
                value: 2,
			},
		]
	])
	const relationshipActions = ref([
		[
			{
				name: '本人'
			},
			{
				name: '子女'
			},
			{
				name: '父母'
			},
		]
	])

    const sexSelect = (e) => {

        model.value.sex = e.value[0].value
        model.value.sexName = e.value[0].name
        // 重新验证
        uForm.value.validateField('sexName')
        showSex.value = false
    }

    onReady(() => {
        uForm.value.setRules(rules)
    })
    const status = ref('')
    // 参数
    const scheduleId = ref(0)
    // 编辑主键
    const patientId = ref(0)

    onLoad((evt) => {
        // 是否登录
        if (!getToken()) {
            uni.showToast({
                mask: true,
                title: '请先登录!',
                icon: 'error'
            })

            const pages = getCurrentPages()
            let fromPath = "/" + pages[pages.length - 1].route + `?patient_id=${patientId.value}&schedule_id=${scheduleId.value}`

            setTimeout(() => {
                // @ts-ignore
                uni.redirectTo({
                    url: "/pages/login/login?fromPath=" + encodeURIComponent(fromPath)
                });
            },800)
        } else {
            console.log('携带参数',evt)
            status.value = evt?.status ?? ''
            patientId.value = evt?.patient_id ?? 0
            scheduleId.value = evt?.schedule_id ?? 0

            if (patientId.value > 0) {
                handleGetPatient()
            }
        }
    })

    const handleGetPatient = async () => {
        const {code, data, message} = await getPatient({id: patientId.value})
        if (code == 1) {
            model.value.name = data.name
            model.value.sex = data.sex
            model.value.age = data.age
            model.value.sexName = data.sex == 1 ? '男' : '女'
            model.value.mobile = data.mobile
            model.value.id_card = data.id_card ?? ''
            model.value.medical_history = data.medical_history ?? ''
            model.value.genetic_history = data.genetic_history ?? ''
            model.value.address = data.address ?? ''
            model.value.relationship = data.relationship ?? ''
            model.value.is_myself = data.is_myself
        } else {
            uni.showToast({
                mask: true,
                title: '获取数据异常',
                icon: 'error'
            })
            setTimeout(() => {
                goBack()
            },500)
        }
    }
	const relationshipSelect = (e) => {
		model.value.relationship = e.value[0].name
        if (e.value[0].name == '本人') {
            model.value.is_myself = 1
        } else {
            model.value.is_myself = 0
        }
		showRelationship.value = false
	}
    const confirm = () => {

        uForm.value.validate().then(async ({ valid }) => {
            if (valid) {
                uni.showToast({
                    mask: true,
                    title: '验证失败',
                    icon: 'error'
                })
                return false
            } else {

                let age = getAge(model.value.id_card);
                //验证成功
                let param = {
                    name: model.value.name,
                    sex: model.value.sex,
                    mobile: model.value.mobile,
                    age: age,
                    is_myself: model.value.is_myself,
                    id_card: model.value.id_card,
                    address: model.value.address,
                    medical_history: model.value.medical_history,
                    genetic_history: model.value.genetic_history,
                    relationship: model.value.relationship,
                }
                if (patientId.value > 0) {
                    param.id = patientId.value
                }

                const {code, data, message} = await savePatient(param)
                if (code === 1) {
                    // uni.navigateBack()
                    if (status.value == 'choose') {
                        uni.redirectTo({
                            url: `/mine/visitor/list?status=${status.value}&schedule_id=${scheduleId.value}`
                        });
                    } else {
                        let pages = getCurrentPages(); // 当前页面
                        let beforePage = pages[pages.length - 2]; // 上一页
                        uni.navigateBack({
                            success: function() {
                                beforePage.onLoad(); // 执行上一页的onLoad里面的方法方法
                            }
                        });
                    }
                } else {
                    uni.showToast({
                        mask: true,
                        title: message ?? '保存失败',
                        icon: 'error'
                    })
                }
            }
        }).catch(err => {
            console.log('验证失败',err)
        });
    }
</script>

<style lang="scss" scoped>
	.container {
		padding: 50rpx 26rpx;

		.form {
			padding: 0 44rpx;
			background: #FFFFFF;
			border-radius: 30rpx;

			.form-item {
				@include between(100%);
				padding: 10rpx 0;

				.left {
					@include start(220rpx);

					&>view {
						color: #B3BCCC;
						font-size: 28rpx;
						margin-left: 16rpx;
					}
				}

				.right {
					flex: 1;
					margin-left: 30rpx;
					display: flex;
					align-items: center;
				}
			}
		}
	}

	.self-set {
		@include end(100%);
	}

	.btn {
		padding: 0 55rpx;
		width: 100%;
		position: fixed;
		left: 50%;
		bottom: 70rpx;
		transform: translateX(-50%);
		z-index: 999;
	}
</style>
